package com.isoftstone.framework;


import com.isoftstone.common.utils.SpringContext;
import com.isoftstone.project.system.dict.service.IDictService;
import com.isoftstone.project.system.domain.SysDict;
import freemarker.template.*;
import org.springframework.stereotype.Component;
import java.util.List;

/**
 * Created by admin on 16/5/11.
 */

@Component
public class GetDict implements TemplateMethodModelEx {

    public static String converString(TemplateModel model) throws TemplateModelException {
        if (null != model) {
            if (model instanceof TemplateScalarModel) {
                return ((TemplateScalarModel) model).getAsString();
            } else if ((model instanceof TemplateNumberModel)) {
                return ((TemplateNumberModel) model).getAsNumber().toString();
            }
        }
        return null;
    }

    @Override
    public Object exec(List list) throws TemplateModelException {

        IDictService sysDictService = SpringContext.getBean(IDictService.class);
        List<SysDict> sysDictList = null;

        if (list.size() == 1) {
            TemplateModel templateModel = (TemplateModel) list.get(0);

            String type = converString(templateModel);
            try {
                sysDictList = sysDictService.getDictByType(type);
            } catch (Exception e) {
                e.printStackTrace();
            }

            return sysDictList;
        }
        if (list.size() == 2) {
            TemplateModel typeModel = (TemplateModel) list.get(0);

            String type = converString(typeModel);

            TemplateModel codeModel = (TemplateModel) list.get(1);

            String code = converString(codeModel);


            try {
                SysDict dict = sysDictService.getDictByTypeAndCode(type, code);

                return dict;
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        return null;

    }
}
